const express = require('express'); //express模块，需要安装
const bodyParser = require('body-parser'); //body-parser模块，需要安装，解析body
const fs = require('fs'); //fs模块
const {
    getBaseData,
    save,
    searchData
} = require('./util/deal_file')
/**
访问目录，如果没有，则创建
*/
var createFolder = (folder) => {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}


//启动express
var app = express()
app.all('*', function (req, res, next) {
    // res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    res.setHeader("Content-Type", "application/json;charset=utf-8");
    next();
})
//使用bodyParser解析头部
app.use(bodyParser.urlencoded({
    extended: false
}))
//使用bodyParser解析json
app.use(bodyParser.json())

const apiData = __dirname + '\\data\\'

//post 使用JSON.stringify解析
app.get('/api/sentence', (req, res) => {
    getBaseData(apiData + 'sentence.json').then((response) => {
        res.send(JSON.stringify(response) + '\n')
    })
    // console.dir(req.query);
    // console.dir(req.body)
    // res.send("post method: " + JSON.stringify(req.query) + '\n')
})
//post 使用JSON.stringify解析
app.post('/api/addSentence', (req, res) => {
    console.dir(req.body)
    save(apiData + 'sentence.json', {
        ...req.body
    }, (err) => {
        if (err) return res.send(err)
        res.send('保存成功')
    })
})
app.post('/api/searchSentence', (req, res) => {
    console.dir(req.body.value);
    searchData(apiData + 'sentence.json', req.body.value).then((response) => {
        res.send(response)

    })
})










//get表单文件，使用fs进行发送
app.get('/form', (req, res) => {
    res.sendFile(__dirname + '/form.html'); //这句话与下面两句话等价
    //var form = fs.readFileSync('./form.html',{encoding:'utf8'});
    //res.send(form)
})


//get 发送头部param的find属性
app.get('/', (req, res) => {
    console.dir(req.query);
    res.send("home page: " + req.query.find)
})

//get 发送OBJ或者动态ID属性
app.get('/profile/:id', function (req, resp) {
    var jsonObj = {
        name: "steve",
        age: '18'
    }
    console.dir(req.params);
    console.dir(jsonObj);
    resp.send("your request to see profile with id of " + req.params.id)
})

//监听端口
app.listen(5000);
console.log('listening to port 5000')